import cv2
import numpy as np
from pathlib import Path
from PIL import Image

def cv2_to_pil(img):
    # 将OpenCV图像转换为PIL图像
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    return Image.fromarray(img)

def pil_to_cv2(img):
    # 将PIL图像转换为OpenCV图像
    img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
    return img

def get_distance(bg_img, tp_img, im_show=False, save_path=None):
    bg_gray = cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY)
    tp_gray = cv2.cvtColor(tp_img, cv2.COLOR_BGR2GRAY)
    tp_gray = cv2.Canny(tp_gray, 255, 255)
    bg_gray = cv2.Canny(bg_gray, 255, 255)
    result = cv2.matchTemplate(bg_gray, tp_gray, cv2.TM_CCOEFF_NORMED)
    _, _, _, max_loc = cv2.minMaxLoc(result)

    distance = max_loc[0]
    if save_path or im_show:
        tp_height, tp_width = tp_gray.shape[:2]
        x, y = max_loc
        _x, _y = x + tp_width, y + tp_height
        cv2.rectangle(bg_img, (x, y), (_x, _y), (0, 0, 255), 2)
        if save_path:
            save_path = Path(save_path).resolve()
            save_path = save_path.parent / f"{save_path.stem}.{distance}{save_path.suffix}"
            save_path = save_path.__str__()
            cv2.imwrite(save_path, cv2.cvtColor(bg_img, cv2.COLOR_RGB2BGR))
        if im_show:
            pil_image = cv2_to_pil(bg_img)
            pil_image.show()
    return distance

if __name__ == '__main__':
    bg_img = cv2.imread('bg.jpg')
    tp_img = cv2.imread('slice.png')
    d = get_distance(
        bg_img=bg_img,
        tp_img=tp_img,
        im_show=False,
    )
    print(d)